﻿using System;
using System.IO;
using System.Web.UI;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
using Student = WebApplication1.domain.Student;

namespace WebApplication1.test{
    public class StuInfoInput{
        public static string upload(string filePath){
            domain.Student[] stu = new domain.Student[100];
            String stuInfo;
            string returnText;
            try{
                using (StreamReader sr = new StreamReader(filePath)){
                    stuInfo = sr.ReadToEnd();
                    Console.WriteLine(stuInfo);
                    string[] studentStr = stuInfo.Split(',');
                    for (int i = 0; i < studentStr.Length; i += 4)
                    {
                        stu[i / 4] = new domain.Student(studentStr[i], studentStr[i + 1], studentStr[i + 2], int.Parse(studentStr[i + 3]));
                    }
                }
                using (MySqlConnection conn = new MySqlConnection(util.MySqlHelper.ConnStr)){
                    conn.Open();
                    for (int i = 0;i< (stu.Length);i++) {
                        if (stu[i] != null) {
                            if (!(stu[i].getNo().Equals(""))){
                                //SQL语句
                                string sql = "insert into student(no,name,class_name,dormitory_id) values('" + stu[i].getNo() + "','" + stu[i].getName() + 
                                    "','" + stu[i].getClassName() + "'," + stu[i].getDormitoryId() + ");";
                                //获得MySsqlCommand
                                MySqlCommand cmd = new MySqlCommand(sql, conn);
                                //执行SQL
                                cmd.ExecuteNonQuery();
                            }
                        }
                    }
                    conn.Close();
                    returnText = "文件已上传";
                }
            }catch (Exception e){
                Console.WriteLine(e.Message);
                returnText = "文件格式不正确或无法读取，请重新上传";
            }
            return returnText;
        }
    }
}